import { Effect, ImmerReducer, Subscription } from 'umi';

export interface UseModelDemoState {
  name: string;
  age?: number
}

export interface UseModelDemoType {
  namespace: 'modelDemo';
  state: UseModelDemoState;
  effects: {
    query: Effect;
    queryAge:Effect;
  };
  reducers: {
    // save: Reducer<UseModelDemoState>;
    // 启用 immer 之后
    save: ImmerReducer<UseModelDemoState>;
    saveAge:ImmerReducer<UseModelDemoState>
  };
  subscriptions: { setup: Subscription };
}

const UseModelDemo: UseModelDemoType = {
  namespace: 'modelDemo',
  state: {
    name: 'dylan',
    age: 0
  },
  effects: {
    *query({ payload }, { call, put }: { call: any; put: any }): any {
      yield put({
        type: 'save',
        payload: payload.name,
      });
    },
    *queryAge({ payload }, { call, put }: { call: any; put: any }): any {
      yield put({
        type: 'saveAge',
        payload: payload.age,
      });
    },
  },
  reducers: {
    save(state: any, action: any) {
      state.name = action.payload;
    },
    saveAge(state: any, action: any) {
      state.age = action.payload;
    }
  },
  subscriptions: {
    setup({ dispatch, history }: { dispatch: any; history: any }) {
      return history.listen(({ pathname }: { pathname: any }) => {
        console.log(pathname);

        if (pathname === '/') {
          dispatch({
            type: 'query',
          });
        }
      });
    },
  },
};

export default UseModelDemo;
